<?php


namespace app\community\elasticSearch\lib;


class buildQueryParams
{
    // 生成查询参数
    protected array $queryParams = [
        'query' => [
            'bool' => [
                'must' => [],
                'must_not' => [],
                'should' => []
            ]
        ],
        'from' => 0,
        'sort' => [],
        'size' => 12,
        'version' => true
    ];

    protected int $page = 1;
    protected int $size = 12;

    /**
     * @return array
     */
    public function getQueryParams(): array
    {

        $this->page = request() -> params('page') ?: $this->page;
        $this->size = request() -> params('rows') ?: $this->size;

        $this->queryParams['size'] = $this->size;
        $this->queryParams['from'] = ($this->size * $this->page) - $this->size;

        return $this->queryParams;
    }

    /**
     * 设置字段
     * @param string $fieldName
     * @param string $keyword
     * @param array $options
     * @return $this
     */
    public function setField(string $fieldName, string $keyword, array $options = []): static
    {
        $options['query'] = $keyword;
        // 设置搜索字段
        $this->queryParams['query']['bool']['should'][]['match'][$fieldName] = $options;
        return $this;
    }

    /**
     * 设置关键词高亮
     * @param array $highlight
     * @return $this
     */
    public function setHighlight(array $highlight): static
    {
        $this->queryParams['highlight'] = $highlight;
        return $this;
    }

    /**
     * @param int $page
     * @return buildQueryParams
     */
    public function setPage(int $page): static
    {
        $this->page = $page;
        return $this;
    }

    /**
     * @param int $size
     * @return buildQueryParams
     */
    public function setSize(int $size): static
    {
        $this->size = $size;
        return $this;
    }

    /**
     * 设置排序
     * @param array $sort
     * @return $this
     */
    public function setSort(array $sort): static
    {
        $this->queryParams['sort'] = $sort;
        return $this;
    }

    /**
     * @return int
     */
    public function getPage(): int
    {
        return $this->page;
    }
}
